package cn.wuxuan.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSON;

import cn.gzsxt.vo.MsgObj;
import cn.wuxuan.service.UserService;
import cn.wuxuan.service.Impl.UserServiceImpl;
import cn.wuxuan.vo.Msg;

@WebServlet("/fileupload.oas")
public class FileUpload extends HttpServlet {
	
	UserService service = new UserServiceImpl();
	private static final long serialVersionUID = 1L;
	
	
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("传过来了");
		resp.setContentType("appliction/json;charset=utf-8");
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		
		if(isMultipart){
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(300*1024);
			
			factory.setRepository(new File("C:/temp"));
			
			
			ServletFileUpload upload = new ServletFileUpload();
			
			upload.setFileItemFactory(factory);
			
			upload.setFileSizeMax(300*1024);
			
			upload.setSizeMax(500*1024);
			
		List<FileItem> list = null;
		try {
			list = upload.parseRequest(req);
		} catch (FileUploadException e) {
			MsgObj msgObj = new MsgObj(0,"服务器异常,稍后再试!!!");
			resp.getWriter().print(JSON.toJSONString(msgObj));
			e.printStackTrace();
		}
		
		for (FileItem fileItem : list) {
			if(fileItem.isFormField()){
				String fieldname = fileItem.getFieldName();
				String value = fileItem.getString("utf-8");
			}else {
				String filename = fileItem.getName();
				String value = fileItem.getString("utf-8");

			
			String uuid = UUID.randomUUID().toString().replace("-", "");
			String extention = FilenameUtils.getExtension(filename);
			 
			String newname = uuid+"."+extention;
					
					
			InputStream input = fileItem.getInputStream();
			String realPath = req.getServletContext().getRealPath("/upload")+"/";
			
			File destFile = new File(realPath);
			if(!destFile.exists()){
				destFile.mkdir();
			}
			OutputStream output = new FileOutputStream(new File(newname));
			IOUtils.copy(input, output);
			
			Msg msg = new Msg(1,"/upload"+newname);
			resp.getWriter().print(JSON.toJSONString(msg));
			
			}
		}
			
		}
	}
}

